<template>
  <div>
    <el-table
      v-loading="state.exportDataLoading"
      style="margin: 6px 0 18px 0"
      border
      :data="state.exportDataCount"
    >
      <el-table-column
        align="center"
        width="90px"
        prop="province"
        label="省份"
      />
      <el-table-column
        :key="item.value"
        v-for="item in state.postNames"
        align="center"
        :label="item.label"
        :valuel="item.value"
      >
        <template #default="{ row }">
          <div>
            <div class="h23">{{ row[item.value] }}</div>
            <div v-if="form.exportType === 2">
              <el-input-number
                style="width: 100%"
                size="small"
                controls-position="right"
                :disabled="!row[item.value]"
                @change="(e) => changeCount(row, item.value)"
                :min="0"
                :max="row[item.value] || 0"
                v-model="row['count' + item.value]"
                :placeholder="`请输入${state.sync ? '同步' : '导出'}数量`"
                type="number"
              ></el-input-number>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="form.exportType === 2" class="mb10">
      <span class="mr6">最大数量</span>
      <el-input-number
        style="width: 150px"
        size="small"
        controls-position="right"
        :step="1"
        :precision="0"
        :min="0"
        :max="state.limitInfo.frozenNumber || 0"
        v-model="state.limitInfo.number"
        :placeholder="`请输入${state.sync ? '同步' : '导出'}数量`"
        type="number"
      ></el-input-number>
      <el-button
        class="ml10"
        @click="updateNumber2"
        size="small"
        type="success"
      >
        更新
      </el-button>
      <el-button
        class="ml10"
        style="display: none"
        @click="getTotal"
        size="small"
        type="success"
      >
        total
      </el-button>
    </div>
    <el-form
      v-if="!state.sync"
      ref="exportRef"
      :model="form"
      :rules="rules"
      class="login-form"
    >
      <el-form-item label="导出类型" prop="exportField">
        <el-select
          placeholder="请选择"
          size="small"
          v-model="form.exportField"
          style="width: 300px"
        >
          <el-option
            v-for="dict in export_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="导出名称" prop="exportName">
        <el-input
          size="small"
          placeholder="请输入"
          v-model="form.exportName"
          style="width: 300px"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="tar">
      <el-button size="small" @click="cancel">关闭</el-button>
      <!-- data summary -->
      <el-button
        v-if="!state.sync"
        size="small"
        @click="handleExport"
        type="primary"
      >
        导出
      </el-button>
      <el-button
        v-if="state.sync"
        :disabled="disabledSync"
        size="small"
        @click="handleExport"
        type="primary"
      >
        同步数据
      </el-button>
    </div>
  </div>
</template>
<script setup>
import {
  getExportData,
  getJobStatus,
  getSyncCompanyInfo,
} from '@/api/uploadFile.js'
import { ElMessage } from 'element-plus'
import { inject, ref } from 'vue'

const { proxy } = getCurrentInstance()
const disabledSync = ref(false)
const rules = {
  exportName: [{ required: true, trigger: 'blur', message: '请选择' }],
  exportField: [{ required: true, trigger: 'blur', message: '请输入' }],
}
const form = ref({
  exportName: '',
  exportField: '',
  exportType: 2,
  restraint: [],
})
const updateNumber2 = () => {
  //  百分比均摊算法
  if (state.limitInfo.number >= state.limitInfo.frozenNumber) {
    state.limitInfo.number = state.limitInfo.frozenNumber
  }
  // const limitArea = {min:100000000000,max:0}
  const percent =
    (state.limitInfo.number || 0) / (state.limitInfo.frozenNumber || 1)
  state.exportDataCount.forEach((_) => {
    if (_.A) {
      _.countA = Math.floor(_.A * percent)
    }
    if (_.B) {
      _.countB = Math.floor(_.B * percent)
    }
    if (_.C) {
      _.countC = Math.floor(_.C * percent)
    }
    if (_.N) {
      _.countN = Math.floor(_.N * percent)
    }
  })
  const total = getTotal()
  let diff = (state.limitInfo.number || 0) - (total || 0)
  if (diff > 0) {
    state.exportDataCount.forEach((_) => {
      if (_.A && diff > 0) {
        const diffA = _.A - (_.countA || 0)
        if (diffA >= diff) {
          // 7 1
          _.countA = (_.countA || 0) + diff
          diff = 0
        } else {
          //  1 7
          diff -= diffA
          if (diff < 0) {
            diff = 0
          }
          _.countA = _.A
        }
      }
      if (_.B && diff > 0) {
        if (_.B - (_.countB || 0) >= diff) {
          _.countB = (_.countB || 0) + diff

          diff = 0
        } else {
          diff -= Math.abs(_.B - _.countB)
          if (diff < 0) {
            diff = 0
          }

          _.countB = _.B
        }
      }
      if (_.C && diff > 0) {
        if (_.C - (_.countC || 0) >= diff) {
          _.countC = (_.countC || 0) + diff
          diff = 0
        } else {
          diff -= Math.abs(_.C - _.countC)
          if (diff < 0) {
            diff = 0
          }

          _.countC = _.C
        }
      }
      if (_.N && diff > 0) {
        if (_.N - (_.countN || 0) >= diff) {
          _.countN = (_.countN || 0) + diff
          diff = 0
        } else {
          diff -= Math.abs(_.N - _.countN)
          if (diff < 0) {
            diff = 0
          }
          _.countN = _.N
        }
      }
    })
  }
}

const updateNumber = () => {
  //  根据最大值计算  平均数算法
  console.log(state)
  if (state.limitInfo.number >= state.limitInfo.frozenNumber) {
    state.limitInfo.number = state.limitInfo.frozenNumber
  }
  if (state.limitInfo.number === state.limitInfo.frozenNumber) {
    state.exportDataCount.forEach((_) => {
      state.postNames.forEach(({ value }) => {
        _['count' + value] = _[value]
      })
    })
  } else {
    // state.exportDataCount.forEach(_=>{})
    const len = state.limitInfo.editorableData.length || 1 // 分母不能为0
    const meanNumber = Math.floor(state.limitInfo.number / len) // 平均数
    console.log(meanNumber)
    state.exportDataCount.forEach((_) => {
      state.postNames.forEach(({ value }) => {
        if (_[value]) {
          _['count' + value] = meanNumber
        }
      })
    })
    requestAnimationFrame(() => {
      getModelNum2()
    })
  }
}
const getTotal = () => {
  let n = 0
  state.exportDataCount.forEach((_) => {
    console.log(_)
    n += (_.countA || 0) + (_.countB || 0) + (_.countC || 0) + (_.countN || 0)
  })
  // alert(n)
  console.log(n)
  return n
}
const getModelNum2 = () => {
  let subtraction = state.limitInfo.number // 差
  console.log(state)
  state.exportDataCount.forEach((_) => {
    subtraction -=
      (_['countA'] || 0) +
      (_['countB'] || 0) +
      (_['countC'] || 0) +
      (_['countN'] || 0)
  })
  console.log(subtraction)
  state.exportDataCount.forEach((item) => {
    if (item.A && subtraction > 0) {
      if (item.A - (item.countA || 0) >= subtraction) {
        item.countA = (item.countA || 0) + subtraction
        subtraction = 0
      } else {
        const duff = item.A - (item.countA || 0)
        item.countA = item.A
        subtraction -= duff
      }
    }
    if (item.B && subtraction > 0) {
      if (item.B - (item.countB || 0) >= subtraction) {
        item.countB = (item.countB || 0) + subtraction
        subtraction = 0
      } else {
        const duff = item.B - (item.countB || 0)
        item.countB = item.B
        subtraction -= duff
      }
    }
    if (item.C && subtraction > 0) {
      if (item.C - (item.countC || 0) >= subtraction) {
        item.countC = (item.countC || 0) + subtraction
        subtraction = 0
      } else {
        const duff = item.C - (item.countC || 0)
        item.countC = item.C
        subtraction -= duff
      }
    }
    if (item.N && subtraction > 0) {
      if (item.N - (item.countN || 0) >= subtraction) {
        item.countN = (item.countN || 0) + subtraction
        subtraction = 0
      } else {
        const duff = item.N - (item.countN || 0)
        item.countN = item.N
        subtraction -= duff
      }
    }
  })
}
// const getModelNum = ()=>{
//     let subtraction = state.limitInfo.number ;  // 差
//    console.log(state)
//     state.exportDataCount.forEach(_=>{
//         subtraction -=  ((_['countA'] || 0) + (_['countB'] || 0) + (_['countC'] || 0) + (_['countN'] || 0));
//     })
//     console.log(subtraction,'subtraction')
//     if(subtraction === 0 ){return}

//     state.exportDataCount.forEach(_=>{
//         subtraction > 0 &&  state.postNames.forEach(({value})=>{
//                if( subtraction > 0 && _[value] -_['count'+value]  >= subtraction ){ // 大于 差值 赋值 并清空差值
//                 _['count'+value]  = subtraction +   _['count'+value]
//                 subtraction = 0
//                }else {  // 小于 差值
//                     if( subtraction > 0){

//                 _['count'+value]  = _[value]
//                 subtraction -= (Math.abs(_[value] - _['count'+value]))
//                 if(subtraction < 0) {
//                     _['count'+value]  +=subtraction
//                 }
//                 }
//                }
//             })
//             })

// }

async function handleExport() {
  const res = await getJobStatus()
  if (res.msg === 'true') {
    ElMessage.error('当前有正在进行中的任务，请稍后再试')
    return
  }

  const fcCompany = state.getParams()
  state.translate(fcCompany, 'postName')
  state.translate(fcCompany, 'province')
  state.translate(fcCompany, 'batchName')
  if (state.exportDataCount.length === 0) {
    let text = fcCompany.province
    if (fcCompany.postName) {
      text = fcCompany.province + '的' + fcCompany.postName + '类型'
    }
    text += '暂无数据，请选择其他数据'
    proxy.$modal.msgError(text)
    return
  }
  let tableData = JSON.parse(JSON.stringify(state.exportDataCount))

  console.log(fcCompany)
  console.log(form.value.exportType)
  if (form.value.exportType === 2) {
    let count = 0
    tableData.forEach((_) => {
      console.log(_)
      if (_.countA || _.countB || _.countC || _.countN) {
        count++
      }
      !_.countA && delete _.countA
      !_.countB && delete _.countB
      !_.countC && delete _.countC
      !_.countN && delete _.countN
      if (!_.countA && !_.countB && !_.countC && !_.countN) {
        _.del = true
      }
    })
    if (count === 0) {
      proxy.$modal.msgError(`请输入数量!`)
      return
    }
    tableData = tableData.filter((_) => !_.del)
    form.value.restraint = []
    tableData.forEach((_) => {
      state.postNames.forEach(({ value }) => {
        const obj = {}
        if (['count' + value] in _) {
          obj.province = _.province
          obj.type = value
          obj.number = _['count' + value]
          form.value.restraint.push(obj)
        }
      })
    })
  }
  disabledSync.value = true
  state.sync &&
    getSyncCompanyInfo({
      ...form.value,
      fcCompany: { ...fcCompany, synced: false },
      exportType: form.exportField,
    })
      .then((res) => {
        proxy.$modal.msgSuccess(res.msg)
        state.visible = false
        proxy.$modal.closeLoading()
      })
      .finally(() => {
        disabledSync.value = false
      })

  !state.sync &&
    proxy.$refs.exportRef.validate((valid) => {
      if (valid) {
        //   loading.value = true;
        proxy.$modal.loading('数据导出中……')
        debugger
        // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
        getExportData({ ...form.value, fcCompany }).then((res) => {
          state.visible = false
          console.log(proxy.$modal)

          proxy.$modal.msgSuccess(res.msg)
          proxy.$modal.closeLoading()
        })
      } else {
      }
    })
}

const changeCount = (obj, k) => {
  console.log(obj[k])
  requestAnimationFrame(() => {
    state.limitInfo.number = getTotal()
  })
}
const cancel = () => {
  state.visible = false
  state.exportDataCount = []
}
const { export_type } = proxy.useDict('export_type')
console.log(export_type)
const state = inject('state')
</script>
<style scoped>
.h23 {
  height: 23px;
}
</style>
